import {postReqLog ,getReq } from "../http";
import {getStore, setStore, removeStore, formatTime} from "../tool";

const AUTH_SUCCESS = 'AUTH_SUCCESS'
const LOGOUT = 'LOGOUT'
const ERROR_MSG = 'ERROR_MSG'
const USER_LIST='USER_LIST'

const initState={
    msg:'',
    user:'',
    isAuth:false,
    redirectTo:'',
    list:[],
}
// reducer
export function user(state=initState, action){
    switch(action.type){
        case USER_LIST:
            return {...state,list:action.payload}
        case AUTH_SUCCESS:
            return {...state, isAuth:true, msg:action.payload.msg, user:action.payload.data,redirectTo:'/home'}
        case ERROR_MSG:
            return {...state,redirectTo:'', isAuth:false, msg:action.msg}
        case LOGOUT:
            return {...initState}
        default:
            return state
    }
}
 function authSuccess(obj){
    setStore('userinfo',obj)
    const {password,status,...data} = obj
    return {type: AUTH_SUCCESS, payload:data}
}
export function loginSuccess(obj) {
    return  dispatch=>{
        dispatch(authSuccess(obj))
    }
}
function errorMsg(msg){
    return { msg, type:ERROR_MSG }
}
export function logoutSubmit(){
     removeStore('userinfo')
    return { type:LOGOUT }
}
export function login({username,password}){
        if (!username||!password) {
            return errorMsg('用户密码必须输入')
        }
        return async dispatch=>{
            let res = await postReqLog('/user/login.do',{username,password})
            if(res.data){
                dispatch(authSuccess(res))
            }else {
                dispatch(errorMsg(res.msg))
            }
        }
}

function getUserList(data) {
    let newList = []
    for(let i = 0; i < data.list.length; i++){
        let item = data.list[i]
        newList.push({...item,key:i+1,createTime:formatTime(new Date(item.createTime))})

    }
    return {type:USER_LIST,payload:{...data, list:newList,current:1}}
}
export function userList(pageNum) {
    return async dispatch=>{
        let res = await getReq('/api/list',{pageNum})
        if(res.data){
            dispatch(getUserList(res.data))
        }
    }

}

